package com.zhouyu.paydemo.unipay.qrcode.BS;

import com.zhouyu.paydemo.unipay.qrcode.DemoBase;
import com.zhouyu.paydemo.unipay.sdk.QrcService;
import com.zhouyu.paydemo.unipay.sdk.SDKConfig;
import com.zhouyu.paydemo.unipay.sdk.SDKConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 用途：申请二维码<br> 日期： 2017-03<br> 声明：以下代码只是为了方便商户测试而提供的样例代码，商户可以根据自己需要，按照技术文档编写。该代码仅供参考，不提供编码，性能，规范性等方面的保障<br>
 */
@Service
@Slf4j
public class ApplyQrNo {

    @PostConstruct
    public void loadSdkConfig(){
        SDKConfig.getConfig().loadPropertiesFromSrc();;
    }

    public void applyQrcode(HttpServletResponse resp)
            throws ServletException, IOException {

        //付款方机构代码
        String issCode = "49995281";
        //账号
        String accNo = "6216261000000000018";
        String name = "zhouyu";
        String mobile = "13560306336";
        String cardAttr = "01";
        String payerBankInfo = "";
        String acctClass = "2";

        String pinFree = "10000";
        String maxAmont = "30000";
        String addnOpUrl = "aewqewqeqw";
        String backUrl = "https://yorkchow.mynatapp.cc/paydemo";

        String emvCodeIn = "0";

        Map<String, String> contentData = new HashMap<String, String>();

        contentData.put("version", "1.0.0");
        contentData.put("reqType", "0210000903");
        contentData.put("issCode", issCode);
        contentData.put("qrType", "35"); //35借记卡   51 贷记卡

        String deviceID = "703388FB-6072-48DF-97E2-4F285D94049D";
        //付款方申码交易主键
        contentData.put("qrOrderNo", DemoBase.getOrderId());
        contentData.put("qrOrderTime", DemoBase.getCurrentTime());

        contentData.put("emvCodeIn", emvCodeIn);

        //riskInfo必送，详细参考规范说明
        HashMap<String, String> riskInfoMap = new HashMap<>();
        riskInfoMap.put("deviceID","123456999");
        riskInfoMap.put("deviceType","1");
        riskInfoMap.put("mobile","13525677809");
        riskInfoMap.put("accountIdHash","00000002");
        riskInfoMap.put("sourceIP","111.13.100.91");
        riskInfoMap.put("usrRgstrDt","20200821");
        String riskInfo = DemoBase.formInfoBase64(riskInfoMap, SDKConstants.UTF_8_ENCODING);

        /*contentData.put("riskInfo", QrcService.base64Encode(
                "{deviceID=123456999&deviceType=1&mobile=13525677809&accountIdHash=00000002&sourceIP=111.13.100.91}",
                DemoBase.encoding));*/
        contentData.put("riskInfo",riskInfo);

        Map<String, String> payerInfoMap = new HashMap<String, String>();
        payerInfoMap.put("accNo", accNo);
		/*if (null != name && !"".equals(name)) {
			payerInfoMap.put("name", name);
		}
		if (null != payerBankInfo && !"".equals(payerBankInfo)) {
			payerInfoMap.put("payerBankInfo", payerBankInfo);
		}*/
        if (null != acctClass && !"".equals(acctClass)) {
            //payerInfoMap.put("acctClass", acctClass);
        }
        payerInfoMap.put("cardAttr", cardAttr);//01 借记卡 02 贷记卡（含准贷记卡）
        payerInfoMap.put("mobile", mobile);//手机号必送
        //敏感信息不加密使用DemoBase.getPayerInfo方法
        contentData.put("payerInfo", DemoBase.getPayerInfo(payerInfoMap, "UTF-8"));

        //如果对机构号issCode 配置了敏感信息加密，必须1.送encryptCertId 2.对payerInfo，payeeInfo的值整体加密
        //目前二维码系统要求所有接入均采用加密方式，使用正式机构号测试的时候参考如下方法上送
        contentData.put("payerInfo", DemoBase.getPayerInfoWithEncrpyt(payerInfoMap,"UTF-8"));
        String encryptCertId = QrcService.getEncryptCertId();
        contentData.put("encryptCertId", encryptCertId);
/*
        if (!"".equals(couponInfo_type) && !"".equals(couponInfo_id)) {
            String couponInfoStr = "[{\"type\": \"" + couponInfo_type + "\", \"id\" : \"" + couponInfo_id
                    + "\"}]"; //可替换使用第三方json库组json
            //付款方适配活动：付款方需要明确指出活动的出资方，允许以下三种情况，即付款方单独出资、付款方与银联共同出资、银联单独出资
            contentData.put("couponInfo", QrcService.base64Encode(couponInfoStr, "UTF-8"));
        }*/

        if ("".equals(pinFree.trim()) && "".equals(maxAmont.trim()) && "".equals(addnOpUrl.trim())) {
            //不送addnCond addnOpUrl
        } else {
            Map<String, String> addnCondMap = new HashMap<String, String>();
            addnCondMap.put("currency", "156"); //金额币种
            addnCondMap.put("pinFree", pinFree);//免密限额
            addnCondMap.put("maxAmont", maxAmont);//最高交易金额
            contentData.put("addnCond", DemoBase.getAddnCond(addnCondMap, "UTF-8")); //附加处理条件
            contentData.put("addnOpUrl", addnOpUrl);//附加处理服务器地址
        }
        String orderId = DemoBase.getOrderId();
        String reqReserved= QrcService.base64Encode(orderId, SDKConstants.UTF_8_ENCODING);
        contentData.put("reqReserved", reqReserved);
        //c2b交易通知发送地址
        contentData.put("backUrl", backUrl);

        Map<String, String> reqData = QrcService.sign(contentData, DemoBase.encoding);
        String requestUrl = SDKConfig.getConfig().getQrcB2cIssBackTransUrl();
        Map<String, String> rspData = QrcService.post(reqData, requestUrl, DemoBase.encoding);

        if (!rspData.isEmpty()) {
            if (QrcService.validate(rspData, DemoBase.encoding)) {
                log.info("验证签名成功");
                String respCode = rspData.get("respCode");
                if (("00").equals(respCode)) {
                    //
                } else {
                    //其他应答码为失败请排查原因
                    //TODO
                }
            } else {
                log.error("验证签名失败");
                //TODO 检查验证签名失败的原因
            }
        } else {
            //未返回正确的http状态
            log.error("未获取到返回报文或返回http状态码非200");
        }
        String reqMessage = DemoBase.genHtmlResult(reqData);
        String rspMessage = DemoBase.genHtmlResult(rspData);
        resp.getWriter().write("</br>请求报文:<br/>" + reqMessage + "<br/>" + "应答报文:</br>" + rspMessage + "");
    }

    public static void main(String[] args) throws IOException {
        String base64Str = "YUxPCKAAAAMzAQEBVw5iFiYQAAAAAkhdUBIgH2MsggIAAJ8QEQcAAQOgAAABCDkwODgwMDE5nyYIVlmJOY6AoHmfJwGAnzYC8t1fNAEB";
    }
}
